//
//  MainViewController.swift
//  SwiftWeiBo
//
//  Created by IMac on 2017/2/7.
//  Copyright © 2017年 IMac. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {

    lazy var composeBtn : UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupChildControllers()
        setupComposeButton()
    }
}

//extension 类似于OC中的分类，在Swift中还可以用来切分代码块
//可以把相近功能的函数，放在一个extension中
//便于代码维护
//注意：和OC的分类一样，extension中不能定义属性
// MARK: - 设置界面
extension MainViewController {
    
    func setupComposeButton() {
        let count = CGFloat(childViewControllers.count)
        
        //如果这里不减1的话两个按钮会有容错点！
        let w = tabBar.bounds.width/count - 1
        
        //CGRectInset(OC) --> 正数向内缩进，负数向外扩张
        composeBtn.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
        
        tabBar.addSubview(composeBtn)

    }
    
    //设置所有控制器
    func setupChildControllers() {
        let array = [
            ["clsName":"HomeViewController","title":"首页","imageName":"home"],
            ["clsName":"MessageViewController","title":"消息","imageName":"message_center"],
            ["clsName":"UIViewController"],
            ["clsName":"DiscoverViewController","title":"发现","imageName":"discover"],
            ["clsName":"MeViewController","title":"我","imageName":"profile"],
            ]
        
        var arrayM = [UIViewController]()
        
        for dict in array {
            arrayM.append(controller(dict: dict))
        }
        
        viewControllers = arrayM
    }
    
    //使用字典创建一个子控制器
    //dict ：信息字典[name,title,imageName]
    private func controller(dict:[String: String]) ->UIViewController {
        //1.取得字典里面内容
        guard let clsName = dict["clsName"],
                 let title = dict["title"],
                 let imageName = dict["imageName"],
                 //Bundle.main.namespace + "." + clsName 项目加空间名称来识别是那个控制器
                 let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as?UIViewController.Type
            else {
                return UIViewController()
        }
        //2.创建视图控制器
        let vc = cls.init()
        
        vc.title = title
        
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        
        let nav = NavigationViewController(rootViewController:vc)
        
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.orange], for: .highlighted)
        
        return nav
        
    }
}


